package com.egg.mall.enums;


import cn.hutool.core.util.ObjectUtil;
import com.egg.common.swagger.annotation.SwaggerDisplayAnnotation;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

/**
 * 属性类型枚举类
 *
 * @author east
 */
@Getter
@SwaggerDisplayAnnotation
@AllArgsConstructor
public enum OrderStateEnum {


    PAY_WAIT("等待支付", "pay_wait"),
    PAY_TIMEOUT("支付超时", "pay_timeout"),
    PAY_WAIT_CANCEL("未支付已取消", "pay_wait_cancel"),

    PAY_FINISH("已支付", "pay_finish"),
    PAY_REFUND_WAIT("申请退款", "pay_refund_wait"),
    PAY_FINISH_CANCEL("已支付已取消", "pay_finish_cancel"),

    DELIVERY_ING("已发货", "delivery_ing"),

    DELIVERY_USER("用户收货", "delivery_user"),
    DELIVERY_AUTO("自动收货", "delivery_auto"),

    EVALUATE_USER("用户评价", "evaluate_user"),
    EVALUATE_AUTO("自动评价", "evaluate_auto"),

    FINISHED("已完成", "finished"),

    ;


    private String message;
    private String code;


    @Override
    public String toString() {
        return message + ":" + code;
    }

    public static OrderStateEnum getByCode(String code) {
        if (ObjectUtil.isEmpty(code)) {
            throw new RuntimeException("状态类型[" + code + "]不存在");
        }
        Optional<OrderStateEnum> any = Arrays.stream(values()).filter(o -> Objects.equals(code, o.getCode())).findAny();
        if (!any.isPresent()) {
            throw new RuntimeException("状态类型[" + code + "]不存在");
        }
        return any.get();
    }

    /**
     * 状态流转
     *
     * @param nextState
     * @return
     */
    public boolean canTransitionTo(OrderStateEnum nextState) {
        // 判断是否可以从当前状态变更到下一个状态
        switch (this) {
            case PAY_WAIT:
                return nextState == PAY_TIMEOUT || nextState == PAY_WAIT_CANCEL;
            case PAY_TIMEOUT:
                return nextState == PAY_WAIT_CANCEL;
            case PAY_WAIT_CANCEL:
                return false;
            case PAY_FINISH:
                return nextState == PAY_REFUND_WAIT || nextState == DELIVERY_ING;
            case PAY_REFUND_WAIT:
                return nextState == PAY_FINISH_CANCEL;
            case PAY_FINISH_CANCEL:
                return false;
            case DELIVERY_ING:
                return nextState == DELIVERY_USER || nextState == DELIVERY_AUTO;
            case DELIVERY_USER:
                return nextState == EVALUATE_USER || nextState == EVALUATE_AUTO;
            case DELIVERY_AUTO:
                return nextState == EVALUATE_USER || nextState == EVALUATE_AUTO;
            case EVALUATE_USER:
                return nextState == FINISHED;
            case EVALUATE_AUTO:
                return nextState == FINISHED;

            default:
                return false;
        }
    }


}
